package cn.leancloud.demo.todo;

import cn.leancloud.*;
import cn.leancloud.json.JSON;
import cn.leancloud.json.JSONObject;
import cn.leancloud.sms.LCSMS;
import cn.leancloud.sms.LCSMSOption;
import cn.leancloud.types.LCNull;
import cn.leancloud.utils.StringUtil;
import com.google.gson.JsonObject;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
import org.springframework.web.servlet.ModelAndView;

import java.util.List;

public class Cloud {

  @EngineFunction("hello")
  public static String hello(@EngineFunctionParam("name") String name) {
    if (name == null) {
      return "What is your name?";
    }
    return String.format("Hello %s!", name);
  }

  @EngineFunction("sendSMS")
  public static String sendSMS(@EngineFunctionParam("mobile") String mobile) {
    if (StringUtil.isEmpty(mobile)) {
      return "What is your name?";
    }
    LCSMSOption option = new LCSMSOption();
    LCSMS.requestSMSCodeInBackground(mobile, option).subscribe(new Observer<LCNull>() {
      @Override
      public void onSubscribe(Disposable disposable) {

      }

      @Override
      public void onNext(LCNull avNull) {
        ;
      }

      @Override
      public void onError(Throwable throwable) {

      }

      @Override
      public void onComplete() {

      }
    });
    return "";
  }


  @EngineFunction("getTodoList")
  public static String getTodoList(@EngineFunctionParam("limit") int limit){
    LCQuery<Todo> query = LCObject.getQuery(Todo.class);
    query.orderByDescending("createdAt");
    query.include("createdAt");
    query.limit(limit);
    List<Todo> todos = query.find();
    return JSON.toJSONString(todos);
  }



    @EngineHook(className = "_User", type = EngineHookType.onLogin)
    public static LCUser userOnLoginHook(LCUser user) throws Exception {
        if ("noLogin".equals(user.getUsername())) {
            throw new Exception("Forbidden");
        } else {
            return user;
        }
    }

    @EngineHook(className = "_User", type = EngineHookType.afterSave)
    public static void userAfterSaveHook(LCUser user) throws Exception {
        user.put("from", "LeanCloud");
        user.save();
    }



}
